<?php

namespace app\admin\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Config;
use jsuphp\Tools;

class Addon extends Base
{
    /**
     * 读取插件列表
     */
    public function index()
    {
        if (!isset($this->param['status']))
            $this->param['status'] = 1;
        $arr = [];
        //未安装数量
        $noinstall_num = 0;
        foreach (scandir(root_path() . 'addons') as $v) {
            if ($v == '.' || $v == '..') continue;
            //检测类是否存在
            $namespace = "\addons\\" . $v . "\Plugin";
            if (!class_exists($namespace)) continue;
            $info = get_addons_info($v);
            if ($info['status'] == 0) {
                $noinstall_num++;
            }
            if (!empty($info['config'])) {
                $info['config_url'] = (string)url($info['config']);
            }
            if (file_exists(root_path() . 'addons/' . $info['name'] . '/config.php')) {
                $info['config_url'] = (string)url('config', ['name' => $info['name']]);
            }

            $arr[] = $info;
        }
        $count = count($arr);
        $page = $this->request->get('page', 1);
        if ($page <= 0) {
            $page = 1;
        }
        $num = 20;
        //最大页数
        $max = ceil($count / $num);
        if ($page > $max) {
            $page = $max;
        }
        $start = ($page - 1) * $num;
        $list = array_slice($arr, $start, $num, true);
        $data = [
            'list' => $list,
            'page' => $page,
            'count' => $count,
            'max' => $max,
            'status' => $this->param['status'],
            'noinstall_num' =>  $noinstall_num
        ];
        return View::fetch('', $data);
    }

    /**
     *  配置插件
     */
    public function config()
    {
        $addons_info = get_addons_info($this->param['name']);
        if (!file_exists(root_path() . 'addons' . DIRECTORY_SEPARATOR . $this->param['name'] . DIRECTORY_SEPARATOR . 'config.php') || $addons_info['status'] != 1) {
            return $this->error('没有安装该插件或没有启动插件配置');
        }

        //读取插件配置
        $addon = get_addons_instance($this->param['name']);
        $list = $addon->getConfig(true);
        if ($this->request->isAjax()) {
            try {
                $addons_name = $this->param['name'];
                unset($this->param['name']);

                //组合配置信息
                foreach ($this->param as $k => $v) {
                    $list[$k]['value'] = $v;
                }
                $file = root_path() . 'addons' . DIRECTORY_SEPARATOR . $addons_name . DIRECTORY_SEPARATOR . 'config.php';
                if (!is_writable($file)) {
                    throw new \Exception($file . '写入失败,权限不足');
                }
                $str = "<?php " . PHP_EOL . "return " . var_export($list, true) . ';';
                file_put_contents($file, $str);
            } catch (\Exception $e) {
                return $this->error($e->getMessage() ?: '保存失败');
            }
            return $this->success('保存成功');
        }
        $data = [
            'list'      =>  $list,
            'trigger'   =>  !empty($list['trigger']) ? $list['trigger'] : []
        ];
        // dump($data);exit;
        return View::fetch('', $data);
    }

    /**
     * 安装插件
     */
    public function install()
    {
        if ($this->request->isAjax()) {

            Db::startTrans();
            try {
                $name = $this->param['name'];
                //安装插件sql
                $this->importsql($name);

                $class_path = '\addons\\' . $name . '\\Plugin';
                if (!class_exists($class_path)) {
                    throw new \Exception($class_path . '类不存在');
                }

                $class = new $class_path($this->app);
                if (method_exists($class, 'install')) {
                    call_user_func_array([$class, 'install'], []);
                }
                $info_ini = root_path() . 'addons/' . $name . '/info.ini';
                $content = parse_ini_file($info_ini);
                $content['status'] = 1;
                $str = '';
                foreach ($content as $k => $v) {
                    $str .= $k . ' = ' . $v . "\n";
                }
                if(!is_writable($info_ini)){
                    throw new \Exception($info_ini.'没有写入权限');
                }
                file_put_contents($info_ini, $str);
                
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage() ?: '安装失败');
            }
            return $this->success('安装成功');
        }
    }

    /**
     * 导入SQL
     *
     * @param   string $name 插件名称
     * @return  boolean
     */
    public function importsql($name)
    {
        $sqlFile = root_path() . 'addons/' . $name  . '/install.sql';
        if (is_file($sqlFile)) {
            $lines = file($sqlFile);
            $templine = '';
            foreach ($lines as $line) {
                if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*')
                    continue;

                $templine .= $line;
                if (substr(trim($line), -1, 1) == ';') {
                    $templine = str_ireplace('jsu_', Config::get('database.connections.mysql.prefix'), $templine);
                    $templine = str_ireplace('INSERT INTO ', 'INSERT IGNORE INTO ', $templine);

                    try {
                        Db::execute($templine);
                    } catch (\PDOException $e) {
                        throw new \Exception($e->getMessage());
                    }
                    $templine = '';
                }
            }
        }
        return true;
    }

    /**
     * 卸载插件
     */
    public function uninstall()
    {
        if ($this->request->isAjax()) {
            Db::startTrans();
            try {
                $name = $this->param['name'];
                $class_path = '\addons\\' . $name . '\\Plugin';
                if (!class_exists($class_path)) {
                    throw new \Exception($class_path . '类不存在');
                }
                $class = new $class_path($this->app);
                if (method_exists($class, 'uninstall')) {
                    call_user_func_array([$class, 'uninstall'], []);
                }
                $info_ini = root_path() . 'addons/' . $name . '/info.ini';
                $content = parse_ini_file($info_ini);
                $content['status'] = 0;
                $str = '';
                foreach ($content as $k => $v) {
                    $str .= $k . ' = ' . $v . "\n";
                }
                if(!is_writable($info_ini)){
                    throw new \Exception($info_ini.'没有写入权限');
                }
                file_put_contents($info_ini, $str);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage() ?: '卸载失败');
            }
            return $this->success('卸载成功');
        }
    }

    public function upload()
    {
        if ($this->request->isAjax()) {

            // 获取表单上传文件
            $files = request()->file();
            try {
                validate(['image' => 'filesize:2048000|fileExt:jpg,png,gif'])->check($files);
                $savename = \think\facade\Filesystem::putFile('topic', $files['image']);
            } catch (\think\exception\ValidateException $e) {
                return $this->error($e->getMessage()?:'上传失败');
            }
            return $this->success('上传成功','','/upload/'.$savename);
        }
    }
}
